package com.digitalbuana.smiles.activity;

import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.AnimationDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.InputType;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.inputmethod.InputMethodManager;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;

import com.digitalbuana.smiles.R;
import com.digitalbuana.smiles.data.AppConstants;
import com.digitalbuana.smiles.dialog.SmilesDefaultDialog;
import com.digitalbuana.smiles.ui.helper.BaseUIActivity;
import com.digitalbuana.smiles.ui.helper.ManagedActivity;
import com.digitalbuana.smiles.utils.FontUtils;
import com.digitalbuana.smiles.utils.RecentUtils;
import com.digitalbuana.smiles.utils.ViewUtilities;
import com.google.android.gcm.GCMRegistrar;

public class RegisterActivity extends BaseUIActivity
implements
OnClickListener
{
	AsyncTask<Void, Void, Void> mRegisterTask;
	
	
	//Code
	private FrameLayout containerWidth;
	private FrameLayout btnShowTerms;
	private FrameLayout btnNext;
	private EditText editCountry;
	private EditText editPhone;
	private CheckBox checkTerms;
	
	//Terms
	private FrameLayout containerBlackTerms;
	private FrameLayout containerTerms;
	private WebView webTerms;
	private FrameLayout btnHideTerms;
	
	//Verification
	private FrameLayout conteinerBlackVeri;
	private FrameLayout btnVeriResend;
	private FrameLayout btnVeriConfirm;
	private EditText editVeriCode;
	
	//Verification
	private FrameLayout conteinerBlackID;
	private EditText editID;
	private EditText editEmail;
	private EditText editFullName;
	private RadioGroup radioSex;
	private EditText editPassword;
	private EditText editPasswordConfirm;
	private CheckBox checkShowPass;
	private FrameLayout btnDoneAccount;
	
	private Animation shake;
	private Animation fadein;
	private Animation fadeout;
	
	
	private String postPhoneNumber="";
	private String contryCode;
	private String phoneNum;
	private String verifyCode="";
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		if (isFinishing())
			return;
		
		setContentView(R.layout.activity_register);
		rootView = (FrameLayout)findViewById(R.id.registerRootView);
		//Casting
		containerWidth = (FrameLayout)findViewById(R.id.registerContainerNumber);
		btnShowTerms = (FrameLayout)findViewById(R.id.registerBtnShowTerms);
		btnNext = (FrameLayout)findViewById(R.id.registerBtnNext);
		editCountry = (EditText)findViewById(R.id.registerEditCountry);
		editPhone = (EditText)findViewById(R.id.registerEditPhone);
		checkTerms = (CheckBox)findViewById(R.id.registerCheckTerms);
		
		
		containerBlackTerms = (FrameLayout)findViewById(R.id.registerContainerBlackTerms);
		containerTerms = (FrameLayout)findViewById(R.id.registerContainerTerms);
		webTerms = (WebView)findViewById(R.id.registerWebTerms);
		btnHideTerms = (FrameLayout)findViewById(R.id.registerBtnHideTerms);
		
		conteinerBlackVeri = (FrameLayout)findViewById(R.id.registerContainerBlackVeri);
		btnVeriResend = (FrameLayout)findViewById(R.id.registerVerificationBtnResend);
		btnVeriConfirm = (FrameLayout)findViewById(R.id.registerVerificationBtnConfirm);
		editVeriCode = (EditText)findViewById(R.id.registerVerificationEditNumber);
		
		conteinerBlackID = (FrameLayout)findViewById(R.id.registerContainerBlackID);
		editID = (EditText)findViewById(R.id.registerIDEditID);
		editEmail = (EditText)findViewById(R.id.registerIDEditEmail);
		editFullName = (EditText)findViewById(R.id.registerIDEditFullName);
		radioSex = (RadioGroup)findViewById(R.id.registerIDRadioSex);
		editPassword = (EditText)findViewById(R.id.registerIDEditPassword);
		editPasswordConfirm = (EditText)findViewById(R.id.registerIDEditPasswordConfirm);
		checkShowPass = (CheckBox)findViewById(R.id.registerIDCheckShowPassword);
		btnDoneAccount  = (FrameLayout)findViewById(R.id.registerIDBtnDone);
		
		//Anim
		shake = AnimationUtils.loadAnimation(this, R.anim.shake);
		fadein = AnimationUtils.loadAnimation(this, R.anim.fadein);
		fadeout = AnimationUtils.loadAnimation(this, R.anim.fadeout);
		
		
		FontUtils.setRobotoFont(context, rootView);
		
		
		//Adding To Listener
		btnNext.setOnClickListener(this);
		btnShowTerms.setOnClickListener(this);
		btnHideTerms.setOnClickListener(this);
		btnVeriResend.setOnClickListener(this);
		btnVeriConfirm.setOnClickListener(this);
		containerBlackTerms.setOnClickListener(this);
		btnDoneAccount.setOnClickListener(this);
		checkShowPass.setOnCheckedChangeListener(new OnCheckedChangeListener() {
			@Override
			public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
				if(isChecked){
					editPassword.setInputType(
							InputType.TYPE_CLASS_TEXT
		                    | InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS);
					editPasswordConfirm.setInputType(
							InputType.TYPE_CLASS_TEXT
	                        | InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS);
				}else {
					editPassword.setInputType(
							InputType.TYPE_TEXT_VARIATION_PASSWORD
	                        | InputType.TYPE_CLASS_TEXT
	                        | InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS);
					editPasswordConfirm.setInputType(
							InputType.TYPE_TEXT_VARIATION_PASSWORD
	                        | InputType.TYPE_CLASS_TEXT
	                        | InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS);
				}
			}
		});
		
		//Animating
		final ImageView imgAnim = (ImageView)findViewById(R.id.registerVerificationImgAnim);
		final ImageView loadingTerms = (ImageView)findViewById(R.id.registerLoadingTerms);
		
		imgAnim.setBackgroundResource(R.drawable.kakatua_kedip_anim);
        loadingTerms.setBackgroundResource(R.drawable.kakatua_junior_anim);
		rootView.post(new Runnable() {
			@Override
			public void run() {
				AnimationDrawable anim = (AnimationDrawable) imgAnim.getBackground();
		        anim.start();
		        AnimationDrawable anim2 = (AnimationDrawable) loadingTerms.getBackground();
		        anim2.start();
			}
		});
		

	}
	
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
	}

	
	private void showTerms(){
		InputMethodManager imm  = (InputMethodManager)context.getApplicationContext().getSystemService(Context.INPUT_METHOD_SERVICE);
	    if(imm.isActive()){
	    	imm.hideSoftInputFromWindow(editVeriCode.getWindowToken(), 0); 
	    }
		containerBlackTerms.setVisibility(View.VISIBLE);
		containerBlackTerms.startAnimation(fadein);
		webTerms.loadUrl(AppConstants.urlTermsPrivacy);

		webTerms.setWebViewClient(new WebViewClient(){
			ImageView loadingTerms = (ImageView)rootView.findViewById(R.id.registerLoadingTerms);
			@Override
			public void onPageFinished(WebView view, String url) {
				super.onPageFinished(view, url);
				loadingTerms.setVisibility(View.GONE);
			}
			@Override
			public void onReceivedError(WebView view, int errorCode,
					String description, String failingUrl) {
				super.onReceivedError(view, errorCode, description, failingUrl);
				loadingTerms.setVisibility(View.GONE);
				webTerms.loadUrl(null);
			}
			@Override
			public void onPageStarted(WebView view, String url, Bitmap favicon) {
				super.onPageStarted(view, url, favicon);
				loadingTerms.setVisibility(View.VISIBLE);
			}
		});
	}
	private void hideTerms(){
		containerBlackTerms.setVisibility(View.GONE);
		containerBlackTerms.startAnimation(fadeout);
	}
	
	private void showVeri(){
		boolean vailid = true;
		if(editCountry.getText().length()<2){
			vailid = false;
			editCountry.startAnimation(shake);
			editCountry.requestFocus();
//			editCountry.setText("62");
		}
		if(editPhone.getText().length()<=6 && vailid){
			vailid = false;
			editPhone.startAnimation(shake);
			editPhone.requestFocus();
		}
		if(!checkTerms.isChecked()  && vailid){
			InputMethodManager imm  = (InputMethodManager)context.getApplicationContext().getSystemService(Context.INPUT_METHOD_SERVICE);
		    if(imm.isActive()){
		    	imm.hideSoftInputFromWindow(editPhone.getWindowToken(), 0); 
		    }
			vailid = false;
			checkTerms.startAnimation(shake);
			checkTerms.requestFocus();
		}
		if(vailid){
			//085714291458
			postPhoneNumber = "";
			contryCode = editCountry.getText().toString();
			phoneNum  = editPhone.getText().toString();
			contryCode = contryCode.replaceAll("[^\\d.]", "");
			phoneNum = phoneNum.replaceAll("[^\\d.]", "");
			if(phoneNum!=null){
				String a_char = ""+phoneNum.charAt(0);
				if(a_char.equals("0")||a_char=="0"){
					String s = phoneNum;
					s = s.substring(1, s.length() - 1);
					phoneNum= s;
				}				
			}
			postPhoneNumber = contryCode+phoneNum;
			List<NameValuePair> postData = new ArrayList<NameValuePair>(1);
			postData.add(new BasicNameValuePair("phone", postPhoneNumber));
			doPostAsync(context, AppConstants.APIVrifySMS, postData, null);
		}

	}
	private void doConfirmVeri(){
		if (editVeriCode.getText().length()<4) {
			editVeriCode.startAnimation(shake);
			editVeriCode.requestFocus();
	    } else {
	    	if(editVeriCode.getText().toString().equals(verifyCode)){
		    	showAccount();
	    	}else {
	    		editVeriCode.startAnimation(shake);
				editVeriCode.requestFocus();
	    	}

	    }
	}
	
	private void doConfirmAccount()
	{
		boolean isMale = true;
		if(radioSex.getCheckedRadioButtonId()==R.id.registerIDRadioOption1){
			isMale=true;
		} else {
			isMale=false;
		}
		boolean isValid = true;
		if(editID.getText().length()<5){
			isValid=false;
			editID.startAnimation(shake);
			editID.requestFocus();
		}
		if(editEmail.getText().length()>=5){
		    String expression = "^[\\w\\.-]+@([\\w\\-]+\\.)+[A-Z]{2,4}$";
		    CharSequence inputStr = editEmail.getText().toString();
		    Pattern pattern = Pattern.compile(expression, Pattern.CASE_INSENSITIVE);
		    Matcher matcher = pattern.matcher(inputStr);
		    if (!matcher.matches()) {
		    	isValid=false;
				editEmail.startAnimation(shake);
				editEmail.requestFocus();
		    }
		}
		if(editEmail.getText().length()<5){
	    	isValid=false;
			editEmail.startAnimation(shake);
			editEmail.requestFocus();
		}
		if(editFullName.getText().length()<5){
	    	isValid=false;
	    	editFullName.startAnimation(shake);
	    	editFullName.requestFocus();
		}
		if(editPassword.getText().length()<5){
	    	isValid=false;
	    	editPassword.startAnimation(shake);
	    	editPassword.requestFocus();
		}
		if(editPasswordConfirm.getText().length()<5){
	    	isValid=false;
	    	editPasswordConfirm.startAnimation(shake);
	    	editPasswordConfirm.requestFocus();
		}
		if(
			!editPasswordConfirm.getText().toString().equals(editPassword.getText().toString())
			&&editPassword.getText().length()>=5&&editPasswordConfirm.getText().length()>=5
			){
	    	isValid=false;
	    	editPasswordConfirm.startAnimation(shake);
	    	editPasswordConfirm.requestFocus();
		}
		
		isValid=true;
		
		if(isValid){
			List<NameValuePair> postData = new ArrayList<NameValuePair>(7);
			postData.add(new BasicNameValuePair("username", editID.getText().toString()));
			postData.add(new BasicNameValuePair("email", editEmail.getText().toString()));
			postData.add(new BasicNameValuePair("fullname", editFullName.getText().toString()));
			postData.add(new BasicNameValuePair("password", editPassword.getText().toString()));
			postData.add(new BasicNameValuePair("phone", editPhone.getText().toString()));
			postData.add(new BasicNameValuePair("country", editCountry.getText().toString()));
			if(isMale){
				postData.add(new BasicNameValuePair("gender", "M"));
			}else {
				postData.add(new BasicNameValuePair("gender", "F"));
			}
			//IMEI
			String deviceImei = RecentUtils.getImei(context);
			postData.add(new BasicNameValuePair("imei", deviceImei));
			//REGID
			GCMRegistrar.checkDevice(context);
			GCMRegistrar.checkManifest(context);
			String regId = GCMRegistrar.getRegistrationId(context);
			if (regId.equals("")){
				postData.add(new BasicNameValuePair("regid", regId));
				doPostAsync(context, AppConstants.APIRegister, postData, null);
			}else {
				Toast.makeText(context, "FAILED GET GCM REGID", Toast.LENGTH_SHORT).show();
			}
		}

	}
	
	@Override
	protected void finishAsync(String result) {
		super.finishAsync(result);
		if(urlKu==AppConstants.APIVrifySMS){
			try {
				JSONObject jsonKu = new JSONObject(result);
				String status = jsonKu.getString("STATUS").toUpperCase(Locale.getDefault());
				String message = jsonKu.getString("MESSAGE").toUpperCase(Locale.getDefault());
				Log.e(AppConstants.TAG, "status : "+status);
				Log.e(AppConstants.TAG, "message : "+message);
				if(status.equals("SUCCESS")){
					conteinerBlackVeri.setVisibility(View.VISIBLE);
					conteinerBlackVeri.startAnimation(fadein);
					verifyCode = jsonKu.getString("CODE").toUpperCase(Locale.getDefault());
					Log.e(AppConstants.TAG, "code : "+verifyCode);
				} else if(message.equals("THIS MOBILE NUMBER IS ALREADY ASSOCIATED WITH AN ACCOUNT")){
					showAccount();
				} else {
					SmilesDefaultDialog dialog = new SmilesDefaultDialog(context, "VERIFICATION ERROR", message);
					dialog.show();
				}
			} catch (JSONException e) {
				SmilesDefaultDialog dialog = new SmilesDefaultDialog(context, "VERIFICATION ERROR", "PLEASE CONTACT SUPPORT");
				dialog.show();
			}
		} else if(urlKu==AppConstants.APIRegister){
			try {
				JSONObject jsonKu = new JSONObject(result);
				String status = jsonKu.getString("STATUS").toUpperCase(Locale.getDefault());
				String message = jsonKu.getString("MESSAGE").toUpperCase(Locale.getDefault());
				Log.e(AppConstants.TAG, "status : "+status);
				Log.e(AppConstants.TAG, "message : "+message);
				if(status.equals("SUCCESS")){
					finish();
					startActivity(LoginActivity.createIntent(context));
				} else {
					SmilesDefaultDialog dialog = new SmilesDefaultDialog(context, "REGISTER ERROR", message);
					dialog.show();
				}
			} catch (JSONException e) {
				SmilesDefaultDialog dialog = new SmilesDefaultDialog(context, "REGISTER ERROR", "PLEASE CONTACT SUPPORT");
				dialog.show();
			}
		}
		urlKu=null;
	}
	
	private void resendVeri(){
		List<NameValuePair> postData = new ArrayList<NameValuePair>(1);
		postData.add(new BasicNameValuePair("phone", postPhoneNumber));
		doPostAsync(context, AppConstants.APIVrifySMS, postData, null);
		
	}
	
	private void hideVeri(){
		conteinerBlackVeri.setVisibility(View.GONE);
		conteinerBlackVeri.startAnimation(fadeout);
//		finish();
//		startActivity(LoginActivity.createIntent(context));
	}
	
	private void showAccount()
	{
		conteinerBlackVeri.setVisibility(View.GONE);
		conteinerBlackID.setVisibility(View.VISIBLE);
		conteinerBlackID.startAnimation(fadein);
	}
	
	@Override
	public void onClick(View v) {
		if(v==btnVeriConfirm){
			doConfirmVeri();
		}else if(v==btnVeriResend){
			resendVeri();
		} else if(v==btnShowTerms){
			showTerms();
		} else if(v==btnHideTerms){
			hideTerms();
		} else if(v==btnNext){
			showVeri();
		} else if(v==containerBlackTerms){
			hideTerms();
		} else if(v==btnDoneAccount){
			doConfirmAccount();
		}
	}
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}
	
	@Override
	public boolean onKeyUp(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			onBackPressed();
			return true;
		}
		return super.onKeyUp(keyCode, event);
	}
	
	
	
	@Override
	public void onBackPressed() {
		if(containerBlackTerms.getVisibility()==View.VISIBLE){
			hideTerms();
		} else if(conteinerBlackVeri.getVisibility()==View.VISIBLE){
			hideVeri();
		} else {
			finish();
		}
	}
	
	@Override
	protected void resettingView() {
		super.resettingView();
		if(viewWidth>=ViewUtilities.GetInstance().convertDPtoPX(context, 500)){
			containerWidth.getLayoutParams().width=ViewUtilities.GetInstance().convertDPtoPX(context, 480);
		}
		//Setting terms
		int widthTerms = (viewWidth*80)/100;
		int heightTerms = (viewHeight*85)/100;
		containerTerms.getLayoutParams().height=heightTerms;
		
		if(widthTerms>=ViewUtilities.GetInstance().convertDPtoPX(context, 480)){
			containerTerms.getLayoutParams().width=widthTerms;
		} else {
			containerTerms.getLayoutParams().width=viewWidth;
		}

		if(viewHeight>=ViewUtilities.GetInstance().convertDPtoPX(context, 300)){
			webTerms.getLayoutParams().height = viewHeight-ViewUtilities.GetInstance().convertDPtoPX(context, 100);
		}
	}
	
	public static Intent createIntent(Context context) {
		return new Intent(context, RegisterActivity.class);
	}



}
